<?php
// +----------------------------------------------------------------------+
// | Author:  Evgeny Leontev <eleontev@gmail.com>                         |
// | Copyright (c) 2005 Evgeny Leontev                                    |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+

class AppController extends Controller
{
	
	var $action = false;
	var $page_to_return;
	
	var $query = array('module'   =>'module',
					   'page'     =>'page',
					   'sub_page' =>'sub_page',
					   'action'   =>'action',
					   'id'       =>'id',
					   'show_msg' =>'show_msg'
					   );
	
	
	var $actions = array('insert'=>'insert',
	                     'update'=>'update',
	                     'delete'=>'delete',
	    				 'status'=>'status',
		    			 'detail'=>'detail'
					     );
	
	var $id_key = 'id';
	
	
	// it should be added to params is isset
	// when we return from good operations or from "cancel" from form
	var $params;
	var $more_params = array('records_per_page', 'sort', 'order', 'letter', 'filter', 
							 'popup', 'field_name', 'field_id', 'referer');
	
	var $custom_return_params = array();
	var $custom_page_to_return;
	
	var $delay_time = '1000'; // js delay time on after action screen
	var $lang = APP_LANG;
	var $module_dir = APP_MODULE_DIR;
	
	var $extra_module_dir = APP_EXTRA_MODULE_DIR;
	var $extra_modules = array();
	
	
	
	function AppController() {
		
		parent::Controller();

		$this->action = $this->getRequestVar('action');
		$this->module = $this->getRequestVar('module');
		$this->page   = $this->getRequestVar('page');
		$this->sub_page = $this->getRequestVar('sub_page');
		
		$this->working_dir = $this->module_dir . $this->module . '/';
		$this->full_page = $this->getFullPageUrl();
		//$this->full_page_params = $this->getFullPageParams();
	}
	
	
	function getRequestVar($var) {
		return @$_GET[$this->query[$var]];
	}
	
	function getRequestKey($key) {
		return @$this->query[$key];
	}
	
	
	function getCurrentLink() {
		$query = $_SERVER['QUERY_STRING'];
		return ($query) ? $_SERVER['PHP_SELF'] . '?' . $query : $_SERVER['PHP_SELF'];
	}
	
	
	function getCommonLink() {
		return $this->full_page;
	}
	
	//full_page
	function setCommonLink($params = array(), $params_to_remove = array()) {
		$this->full_page = $this->full_page . '&' . http_build_query($params);
	}
	
	
	function getAction() {
		return $this->action;
	}
	
	
	// to change values for action key
	function setCustomAction($action, $value) {
		$this->actions[$action] = $value;
	}
	
	
	function getActionValue($action_key) {
		return $this->actions[$action_key];
	}
	
	function setCustomPageToReturn($page, $unserialize = true) {
		$this->custom_page_to_return = ($unserialize) ? WebUtil::unserialize_url($page): $page;
	}	
	
	
	function getFullPageUrl() {
		$p[] = &$this->getParams();
		$p[] = &$this->getMoreParams();
		
		return $_SERVER['PHP_SELF'] . '?' . implode('&', $p);
	}
	
	
	function getFullPageParams() {
		$p[] = &$this->getParams();
		$p[] = &$this->getMoreParams();		
		
		return implode('&', $p);
	}
	
	// set js delay time on after action screen
	// for $multiplier use 0.5, 1, 2 so on 
	// it will set delay time = 1000*$multiplier
	function setDelayTime($multiplier) {
		$this->delay_time = $this->delay_time*$multiplier;
	}
	
	
	// to generate main part of link
	function &getParams() {
		
		//$arr = array('module','page','sub_page');
		$get_str = array();

		$var = (isset($_GET[$this->query['module']])) ? $_GET[$this->query['module']] : false;
		if($var !== false) {
			$get_str[] = sprintf('%s=%s', $this->query['module'], $var);
		}		
		
		$var = (isset($_GET[$this->query['page']])) ? $_GET[$this->query['page']] : false;
		if($var !== false) {
			$get_str[] = sprintf('%s=%s', $this->query['page'], $var);
		}
		
		$var = (isset($_GET[$this->query['sub_page']])) ? $_GET[$this->query['sub_page']] : false;
		if($var !== false) {
			$get_str[] = sprintf('%s=%s', $this->query['sub_page'], $var);
		}	
		
		return implode('&', $get_str);
	}

	
	function &getMoreParams() {
		
		$params = array();	
		foreach($this->more_params as $v) {
			if(isset($_GET[$v])) {
				$params[$v] = $_GET[$v];
			}
		}
		
		return http_build_query($params);
	}

	
	// set one more more param
	//  more params always stay in GET if initialized
	function setMoreParams($val) {
		$this->more_params[] = $val;
	}
	
	
	function getMoreParam($param) {
		return (!empty($_GET[$param])) ? $_GET[$param] : false;
	}
	
	
	function go($msg = 'success', $same_page = false) {
		
		// means on the same page dispaly message
		// message generated in AppView::commonHeaderList()
		if($same_page) {
			$params = array($this->getRequestKey('show_msg') => $msg);	
			$page = $this->full_page . '&' . http_build_query($params);
			header("location: $page");
			exit();
		}
		
		$page_to_return = WebUtil::serialize_url($this->full_page);
		if($this->custom_page_to_return) {
			$page_to_return = WebUtil::serialize_url($this->custom_page_to_return);
		}
		
 		$params = array('msg' => $msg, 
		                'page_to_return' => $page_to_return,
						'delay_time' => $this->delay_time);		
		
		$page = APP_HOME_PATH . 'good_action.php?' . http_build_query($params);
		header("location: $page");
		exit();
	}

	
	function setWorkingDir($dirs = array()) {
	
		$ar[] = (isset($dirs['sub_page'])) ? $dirs['sub_page'] : $this->sub_page;
		$ar[] = (isset($dirs['page']))     ? $dirs['page']     : $this->page;
		$ar[] = (isset($dirs['module']))   ? $dirs['module']   : $this->module;
		
		if(!file_exists($this->module_dir . 'config_path.php')) { return; }
		require_once $this->module_dir . 'config_path.php';
		
		foreach($ar as $k => $v) {
			if(isset($conf_module[$v])){
				if(strpos($conf_module[$v], '{') !== false) {
					$this->working_dir = str_replace('{extra_dir}', $this->extra_module_dir, $conf_module[$v]);
				} else {
					$this->working_dir = $this->module_dir . $conf_module[$v];
				}
				
				break;
			}
		}
	}
	

/*
	// strip all before _ if any, to find module, page or subpage name
	function getName($string) {
		$pos = strpos($string, '_');
		if($pos != false) {
			return $string = substr($string, $pos+1); 
		}
		
		return $string;
	}
*/
	
	
	function getLink($module = false, $page = false, $sub_page = false, $action = false, $more = array()) {
		if($view == 'all') {
			return $this->_getLink($this->getRequestVar('module'), 
			                       $this->getRequestVar('page'), 
								   $this->getRequestVar('sub_page'), 
								   $this->getRequestVar('action')
								   ); 	
		} else {
			return $this->_getLink($module, $page, $sub_page, $action, $more);
		}
	}
	
	
	function _getLink($module = false, $page = false, $sub_page = false, $action = false, $more = array()) {
		
		if($module)     { $link[1] = sprintf('%s=%s', $this->getRequestKey('module'),   $module); }
		if($page)       { $link[2] = sprintf('%s=%s', $this->getRequestKey('page'),     $page); }
		if($sub_page)   { $link[3] = sprintf('%s=%s', $this->getRequestKey('sub_page'), $sub_page); }
		if($action)     { $link[4] = sprintf('%s=%s', $this->getRequestKey('action'),   $action); }			
		
		$link = (@!$link) ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'] . '?' . implode('&', $link);
		$link .= ($more) ? '&' . http_build_query($more) :  '';
		
		return $link;
	}
	
	
/*
	function go($view = false, $category_id = false, $entry_id = false, $msg_key = false) {
		$url = $this->getLink($view, $category_id, $entry_id, $msg_key);
		header("Location: " . $url);
		exit();
	}
*/
	
	
	function goView(&$obj, &$manager, $class, $values = array()) {
		
		require_once $this->working_dir . 'inc/' . $class . '.php';
		
		$view = &new $class;
		$view->execute($obj, $manager, $values);
		
	}
	
	
	function &getView(&$obj, &$manager, $class, $values = array()) {
	
		require_once $this->working_dir . 'inc/' . $class . '.php';
	
		$view = &new $class;
		return $view->execute($obj, $manager, $values);
	}
	
	
	// trying to load default classes
	// look in module dir and extra module dir
	function loadClass($class_name, $path = false) {
		
		$class_name = $class_name . '.php';
		
		if($path) {
			$p[] = $this->module_dir . $path . '/inc/';
			$p[] = $this->extra_module_dir . $path . '/inc/';
			
			foreach($p as $v) {
				if(file_exists($v . $class_name)) {
					require_once $v . $class_name;
				}
			}
		} else {
			require_once $this->working_dir . 'inc/' . $class_name;
		}
	}
	
	
	function loadClasses($class_names) {
		foreach($class_names as $k => $v) {
			$path = (!is_numeric($k)) ? $k : false;
			$this->loadClass($v, $path);
		}
	}
	
	
/*
	function loadDefaultClasses() {
		//$classes = array();
		$this->default_class = 'FileCategory';
		$this->default_classes = array('Model', 'View_list', 'View_form');
		
		$this->loadClasses($this->getDefaultClasses());
	}
	
	function setDefaultClass($name) {
		$this->default_class = $name;
	}
	
	function setMoreDefaultClasses($name) {
		
		$names = (is_array($name)) ? $name : func_get_arg();
		foreach($names as $v) {
			$this->default_classes[] = $v;
		}
	}
	
	function getDefaultClasses() {
		
		$arr[] = $this->default_class;
		foreach($this->default_classes as $v) {
			$arr[] = $this->default_class . $v;
		}
		
		return $arr;
	}
*/
	
}
?>